import { NextRequest, NextResponse } from 'next/server';
import { writeFile, mkdir } from 'fs/promises';
import path from 'path';

export async function POST(request: NextRequest) {
  try {
    const formData = await request.formData();
    const files = formData.getAll('files') as File[];
    
    if (files.length === 0) {
      return NextResponse.json({ success: false, error: '没有文件上传' }, { status: 400 });
    }

    const uploadsDir = path.join(process.cwd(), 'public', 'uploads');
    
    // 确保uploads目录存在
    try {
      await mkdir(uploadsDir, { recursive: true });
    } catch (error) {
      // 目录已存在，忽略错误
    }

    const uploadedFiles: string[] = [];

    for (const file of files) {
      if (file.size === 0) continue;
      
      const bytes = await file.arrayBuffer();
      const buffer = Buffer.from(bytes);
      
      // 生成唯一文件名
      const timestamp = Date.now();
      const randomString = Math.random().toString(36).substring(2, 15);
      const fileName = `${timestamp}-${randomString}-${file.name}`;
      const filePath = path.join(uploadsDir, fileName);
      
      await writeFile(filePath, buffer);
      uploadedFiles.push(`/api/uploads/${fileName}`);
    }

    return NextResponse.json({
      success: true,
      data: {
        files: uploadedFiles
      }
    });
  } catch (error) {
    console.error('文件上传错误:', error);
    return NextResponse.json(
      { success: false, error: '文件上传失败' },
      { status: 500 }
    );
  }
}